#!/usr/bin/env expect

array set hosts {
    1 server1
    2 server2
    3 server3
    4 server4
    5 server5
}

source  credentials.tcl
set     username    [exec whoami]
set     prompt      "(~|#|%|>|\\\$) $"

for {set i 1} {$i < 15} {incr i 1} {
    spawn ssh $hosts($i)
    expect {
        "assword:" { send "$password\n"; }
        "yes/no"   {
            send   "yes\n";
            expect "assword:";
            send   "$password\n";
        }
    }
    expect  -re $prompt;
    send    "sudo su - root\n";
    expect  "assword:";
    send    "$password\n";
    expect  -re $prompt;
    send    "cp .ssh/authorized_keys .ssh/authorized_keys.bak\n";
    expect  -re $prompt;
    send    "cat /home/$username/.ssh/id_rsa.pub >> .ssh/authorized_keys\n";
    expect  -re $prompt;
    send    "diff .ssh/authorized_keys .ssh/authorized_keys.bak\n";
    expect  "$username";
    expect  -re $prompt;
    send    "rm .ssh/authorized_keys.bak\n";
    expect  -re $prompt;
    send    "exit\n";
    expect  -re $prompt;
    send    "exit\n";
    expect  -re $prompt;
    spawn   ssh "root\@$hosts($i)";
    expect  "id_rsa";
    send    "$key\n";
    expect  -re $prompt;
    send    "exit\n";
    expect  "closed."
    interact
}
